﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Besture.Bll;
using Besture.Common.Definition;
using Besture.Model;
using Besture.Utils;
using Besture.Common;

namespace Besture.UI.Ajax
{
    public partial class AjaxPage : System.Web.UI.Page, System.Web.SessionState.IRequiresSessionState
    {
        public StringBuilder Text = null;
        public DataTable dt = null;
        private HttpCookie Cookie = null;
        /// <summary>
        /// 用户Id
        /// </summary>
        protected int UserId
        {
            get { return HttpContext.Current.Session[Constants.SESSION_KEY_LOGIN_USER] == null ? 0 : ((UserModel)HttpContext.Current.Session[Constants.SESSION_KEY_LOGIN_USER]).ID; }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    //注册
                    if (Request.QueryString["Mobile"] != "")
                    {
                        //验证邮箱是否在数据库存在
                        if (Request.QueryString["Mobile"] != null)
                        {
                            dt = new DataTable();
                            UserDac dac = new UserDac();
                            dt = dac.GetDataTable(Request.QueryString["Mobile"]);
                            //如果存在返回1
                            if (dt.Rows.Count > 0)
                            {
                                Response.Write("1");
                                return;
                            }
                            else
                            {
                                Response.Write("0");
                                return;
                            }
                        }
                    }
                    //发送验证短信
                    if (Request.QueryString["SendSMS"] != null)
                    {
                        var Code = Fun.GetCode();
                        Session["SMSCode"] = Code;
                        string flag = SendSMSUtil.SendSMS(Request.QueryString["SendSMS"], string.Format(AppConfig.SMSTemplate, Code));
                        if (flag == "发送成功")
                        {
                            Response.Write("1");
                        }
                        else
                        {
                            Response.Write(flag);
                        }
                    }
                    //发送找回密码验证短信
                    if (Request.QueryString["SendSMSF"] != null)
                    {
                        var Code = Fun.GetCode();
                        Session["SMSCode"] = Code;
                        string flag = SendSMSUtil.SendSMS(Request.QueryString["SendSMSF"], string.Format(AppConfig.SMSCipherTemplate, Code));
                        if (flag == "发送成功")
                        {
                            Response.Write("1");
                        }
                        else
                        {
                            Response.Write(flag);
                        }
                    }
                    //注册
                    if (Request.QueryString["Email"] != null)
                    {
                        //验证邮箱是否在数据库存在
                        if (Request.QueryString["Email"] != null)
                        {
                            UserDac dac = new UserDac();
                            UserModel model = dac.GetModel(Request.QueryString["Email"], null);
                            //如果存在返回1
                            if (model != null)
                            {
                                Response.Write("1");
                                return;
                            }
                            else
                            {
                                model = new UserModel();
                                model = new UserDac().GetModel(UserId);
                                model.Email = Request.QueryString["Email"];
                                model.UpdateBy = UserId;
                                model.UpdateTime = DateTime.Now;
                                new UserDac().UpdateEmail(model);
                                Response.Write("0");
                                return;
                            }
                        }
                    }
                    //激活邮箱
                    if (Request.QueryString["SendEmail"] != null)
                    {
                        string Email = Request.QueryString["SendEmail"];
                        //发送邮件
                        if (Email != null)
                        {
                            SendMail(Email);
                            Response.Write("1");
                            return;
                        }
                    }

                }
            }
            catch (Exception exception)
            {
                Response.Write(exception.ToString());
                Response.End();
                throw;
            }
            finally
            {
                Response.End();
            }
        }
        /// <summary>
        /// MD5加密算法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetMD5String(string str)
        {
            MD5 md5 = MD5.Create();
            byte[] b = Encoding.UTF8.GetBytes(str);
            byte[] md5b = md5.ComputeHash(b);
            md5.Clear();
            StringBuilder sb = new StringBuilder();
            foreach (var item in md5b)
            {
                sb.Append(item.ToString("x2"));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        private void SendMail(string Email)
        {
            var url = "<a href='http://" + Request.Url.Authority + "/User/UserInfo.aspx?Email=" +
                      EncryptUtil.DesEncrypt(Email.Trim()) + "'>http://" + Request.Url.Authority +
                      "/User/UserInfo.aspx?Email=" + EncryptUtil.DesEncrypt(Email.Trim()) + "</a>";
            var urls = "http://" + Request.Url.Authority + "/User/UserInfo.aspx?Email=" +
                       EncryptUtil.DesEncrypt(Email.Trim());
            string content = @"
                                    <p>亲爱的用户：</p>

                                    <p>您好！</p>

                                    <p>您在" + DateTime.Now + @"提交了验证NatureHouse邮箱的请求，请点击下面的链接确认验证。

                                    " +
                             url + @"</p>

                                    <p>(如果您无法点击此链接，请将它复制到浏览器地址栏后访问)</p>

                                    <p>为了保证您帐号的安全，本链接24小时后失效！</p>
                                     ";
            var passWordLinkDac = new PassWordLinkDac();
            var passWordLinkModel = new PassWordLinkModel
            {
                LinkUrl = urls,
                IsDeleted = false,
                Creator = Email,
                Created = DateTime.Now,
                Mender = Email,
                Modified = DateTime.Now
            };
            passWordLinkDac.Add(passWordLinkModel);
            string email = Email.Trim();
            string title = "NatureHouse邮箱验证";
            EmailUtil.SendEmail(email, title, content);
        }
    }
}